package com.diorsunion.hedge.io.netty;

import com.diorsunion.hedge.io.kyro.KryoSerialization;
import com.diorsunion.hedge.io.kyro.KryoFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;

import java.io.IOException;

public class KryoPool {
	
	private static final byte[] LENGTH_PLACEHOLDER = new byte[4];
	
	private KryoFactory kryoFactory;
	
	public KryoPool(int maxTotal,int minIdle,long maxWaitMillis,long minEvictableIdleTimeMillis) {
		kryoFactory = new KryoFactory(maxTotal, minIdle, maxWaitMillis, minEvictableIdleTimeMillis);
	}
	
	public void encode(final ByteBuf out, final Object message) throws IOException {
		ByteBufOutputStream bout = new ByteBufOutputStream(out);
		bout.write(LENGTH_PLACEHOLDER);
		KryoSerialization kryoSerialization = new KryoSerialization(kryoFactory);
		kryoSerialization.serialize(bout, message);
	}
	
	public Object decode(final ByteBuf in) throws IOException {
		KryoSerialization kryoSerialization = new KryoSerialization(kryoFactory);
		return kryoSerialization.deserialize(new ByteBufInputStream(in));
	}
}
